﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpShare.Afp.Protocol.Handlers {
    [Flags]
    public enum AfpServerMessageBitmap : short {
        kSrvrMsg = 0x1,
        kUTF8SrvrMsg = 0x2
    }

    internal class AfpGetServerMessageRequestHandler : IAfpRequestHandler {
        public byte CommandCode {
            get { return 38; }
        }

        public AfpResultCode Process(IAfpSession session, DsiHeader dsiHeader, AfpStream requestStream, AfpStream responseStream) {
            requestStream.ReadPadding();

            short type = requestStream.ReadInt16(); // 0 = Login, 1 = Server
            AfpServerMessageBitmap bitmap = requestStream.ReadEnum<AfpServerMessageBitmap>();

            if (!bitmap.HasFlag(AfpServerMessageBitmap.kSrvrMsg)) {
                return AfpResultCode.FPParamErr;
            }

            responseStream.WriteInt16(type);
            responseStream.WriteEnum(bitmap);

            AfpSessionMessageType messageType;

            switch (type) {
                case 0: messageType = AfpSessionMessageType.Login;
                    break;
                case 1:
                    messageType = AfpSessionMessageType.Server;
                    break;
                default:
                    return AfpResultCode.FPParamErr;
            }

            string message = session.DequeueMessage(messageType);

            if (message == null) {
                message = string.Empty;
            }

            if (bitmap.HasFlag(AfpServerMessageBitmap.kUTF8SrvrMsg)) {
                responseStream.WriteUTF8String(message);
            } else {
                responseStream.WritePascalString(message);
            }

            return AfpResultCode.FPNoErr;
        }
    }
}
